/**
 * admin/api-adapter
 */

const URL = require('url');
const axios = require('axios');
const lodash = require('lodash');
const passport = require('passport');

const signature = require('../../lib/signature');
const apiCfg = require('../../data/subapps')[1];

module.exports = function(app) {
    const apiRouter = app.apiRouter;
    const apiRouterPrefix = apiRouter.opts.prefix || '';
    const adapterMethods = ['get', 'post', 'put', 'delete'];

    const API_HOST = process.env.API_HOST;
    const protocol = /\bdev\b/.test(API_HOST)
        ? 'http://'
        : 'https://';

    const api = axios.create({
        baseURL: protocol + API_HOST
    });

    // signature
    api.interceptors.request.use(config => {
        let timestamp = Math.floor(Date.now() / 1000);
        let urlData = URL.parse(config.url, true);
        let query = lodash.assign({},
            urlData.query,
            config.params
        );

        let sign = signature({
            appId: apiCfg.id,
            appSecret: apiCfg.secret,
            method: config.method,
            timestamp: timestamp,
            path: urlData.path,
            body: config.data,
            query: query
        });

        // set header
        lodash.assign(config.headers.common, {
            'X-Appid': apiCfg.id,
            'X-Timestamp': timestamp,
            'X-Signature': sign
        });

        return config;
    });

    apiRouter.register('(.*)', adapterMethods, function *(next) {
        // admin request process
        yield next;

        // default process
        if(!this.body && this.status === 404) {
            // auth
            yield passport.authorized();

            // adapter to api
            let url = this.path.slice(apiRouterPrefix.length);
            let res = yield api.request({
                method: this.method,
                data: this.request.body,
                params: lodash.clone(this.query),
                url: url,
                headers: {
                    'x-user': this.req.user.get('id'),
                }
            })
            .catch(err => {
                if(err.response) {
                    return err.response;
                }

                throw err;
            });

            // headers
            if(res.headers['x-pagination']) {
                this.set('X-Pagination', res.headers['x-pagination']);
            }

            // yield require('bluebird').delay(2000);

            this.status = res.status || 404;
            this.body = res.data;
        }
    });
};
